<template>
  <div>
    <q-dialog v-model="diag">
      <div>
        <StockItemEdocForm
          @submit="initData()"
          mode="create"
          @close="diag = false"
          :stock_code="props.stockCode"
        ></StockItemEdocForm>
      </div>
    </q-dialog>
    <q-dialog v-model="editDiag">
      <div>
        <StockItemEdocForm
          @submit="initData()"
          mode="edit"
          @close="editDiag = false"
          :id="id"
        ></StockItemEdocForm>
      </div>
    </q-dialog>
    <div class="row justify-end q-mb-md">
      <q-btn
        class="default-btn"
        label="Create"
        @click="diag = true"
        v-if="props.editable"
      />
    </div>
    <ScrollArea :bot-margin="50">
      <div class="sub-header">
        {{ 'Edoc List' }}
      </div>
      <q-table
        class="card-radius my-table"
        wrap-cells
        :rows="sEdocs"
        :columns="cols"
        :rows-per-page-options="[5]"
        @row-dblclick="dblclickFn"
      >
        <template v-slot:body-cell-action="props">
          <q-td>
            <div class="row justify-start">
              <q-btn
                class="edit-btn"
                icon="edit"
                flat
                round
                @click="editFn(props.row.id)"
              />
              <q-btn
                class="del-btn"
                icon="delete"
                flat
                round
                @click="deleteFn(props.row.id)"
              />
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-doc_name="props">
          <q-td>
            <div class="row justify-start items-center">
              <template v-if="props.row.file">
                <q-icon name="attach_file" /><a
                  :href="djangoUrl + props.row.file"
                  target="_blank"
                  >{{ props.row.doc_name }}</a
                >
              </template>
              <template v-else>
                {{ props.row.doc_name }}
              </template>
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-complete="props">
          <q-td
            :class="{
              fail: props.value == false,
            }"
          >
            {{ props.value ? 'Completed' : 'Not Complete' }}
          </q-td>
        </template>
      </q-table>
      <div class="sub-header" v-if="sEdocsChilds.length > 0">
        Childs Edocs List
      </div>
      <q-table
        v-if="sEdocsChilds.length > 0"
        class="card-radius my-table"
        wrap-cells
        :rows="sEdocsChilds"
        :columns="cols"
        :rows-per-page-options="[5]"
        @row-dblclick="dblclickFn"
      >
        <template v-slot:body-cell-action="props">
          <q-td>
            <div class="row justify-start">
              <q-btn
                class="edit-btn"
                icon="edit"
                flat
                round
                @click="editFn(props.row.id)"
              />
              <q-btn
                class="del-btn"
                icon="delete"
                flat
                round
                @click="deleteFn(props.row.id)"
              />
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-doc_name="props">
          <q-td>
            <div class="row justify-start items-center">
              <template v-if="props.row.file">
                <q-icon name="attach_file" /><a
                  :href="djangoUrl + props.row.file"
                  target="_blank"
                  >{{ props.row.doc_name }}</a
                >
              </template>
              <template v-else>
                {{ props.row.doc_name }}
              </template>
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-complete="props">
          <q-td
            :class="{
              fail: props.value == false,
            }"
          >
            {{ props.value ? 'Completed' : 'Not Complete' }}
          </q-td>
        </template>
      </q-table>
    </ScrollArea>

    <q-dialog full-width v-model="edocHistory">
      <MyBigDialog title="Parts EDoc History" content="" mode="">
        <PartsEDocTable
          :part_ids="part_ids"
          :doc_name="editRow.doc_name"
        ></PartsEDocTable>
        <!--   :filter="{ parts: props.part_id, doc_name: editRow.doc_name }" -->
      </MyBigDialog>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  deleteStockItemEdocs,
  getStockItemEdocs,
} from 'src/services/edocService';
import { PartsEDoc, StockItemEDoc } from 'src/services/type';
import { onMounted, ref } from 'vue';
import StockItemEdocForm from './StockItemEDocForm.vue';
import { useQuasar } from 'quasar';
import { resolveDjangoUrl } from 'src/boot/axios';
import { listPartsEDocs, listChildPartsEdocs } from 'src/services/partsEDocService';
import PartsEDocTable from './PartsEDocTable.vue';
import ScrollArea from 'src/components/ScrollArea.vue';
import MyBigDialog from '../container/MyBigDialog.vue';
import { getChildPartsList } from 'src/services/partsService';

const props = withDefaults(
  defineProps<{
    stockCode: string;
    serialNo?: string;
    part_id?: number;
    editable: boolean;
    onClickable: boolean;
    mode: 'stock' | 'part';
  }>(),
  {
    editable: true,
    onClickable: false,
    mode: 'stock',
  }
);

const djangoUrl = resolveDjangoUrl();
const $q = useQuasar();
const id = ref(0);
const diag = ref(false);
const editDiag = ref(false);
const editRow = ref();
const edocHistory = ref(false);
const sEdocs = ref<StockItemEDoc[]>([]);
const sEdocsChilds = ref<StockItemEDoc[]>([]);
const pEdocs = ref<PartsEDoc[]>([]);
const childPartsEdocs = ref<PartsEDoc[]>([]);
const align = 'left';
const cols = [
  {
    name: 'description',
    label: 'Short Description',
    field: 'description',
    format: (val, row) => {
      return row.stock_item.description;
    },
    sortable: true,
    align,
  },
  {
    name: 'doc_name',
    label: 'Doc Name',
    field: 'doc_name',
    sortable: true,
    align,
  },
  {
    name: 'version',
    label: 'Version',
    field: 'version',
    sortable: true,
    align,
  },
];
if (props.editable) {
  cols.push({
    name: 'action',
    label: 'Action',
    sortable: true,
    field: 'action',
    align,
  });
}
if (props.onClickable) {
  cols.push({
    name: 'complete',
    label: 'Status',
    field: 'complete',
    sortable: true,
    align,
  });
}

const part_ids = ref<number[]>();
const childs = ref<Parts[]>([]);

async function initData() {
  
  
  const edocs = await getStockItemEdocs(props.stockCode);
  pEdocs.value = await listPartsEDocs({ invalid: 0, parts: props.part_id });
  console.log(edocs);
  console.log(pEdocs);
  const part_ids = childs.value
    .filter((i) => i.stock_code != props.stockCode)
    .map((v) => v.id);

    console.log(part_ids);
    
  childPartsEdocs.value = await listChildPartsEdocs(part_ids, 0);
  console.log(childPartsEdocs.value);
  sEdocs.value = edocs
    .filter((i) => i.stock_code == props.stockCode)
    .map((item) => {
      return {
        ...item,
        complete:
          pEdocs.value.filter(
            (e) =>
              e.doc_name == item.doc_name &&
              e.version == item.version &&
              e.complete == 1
          ).length > 0,
      };
    });
  sEdocsChilds.value = edocs
    .filter((i) => i.stock_code != props.stockCode)
    .map((item) => {
      return {
        ...item,
        complete:
        childPartsEdocs.value.filter(
            (e) =>
              e.doc_name == item.doc_name &&
              e.version == item.version &&
              e.complete == 1 &&
              e.stock_code == item.stock_code
          ).length > 0,
      };
    });
}

function editFn(sie_id: number) {
  id.value = sie_id;
  editDiag.value = true;
}
function dblclickFn(evt: any, row: StockItemEDoc, index: number) {
  if (props.mode == 'stock') {
    id.value = row.id;
    editDiag.value = true;
  }
  if (props.mode == 'part') {
    onclick(evt, row);
  }
}
function deleteFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    const res = await deleteStockItemEdocs(id);
    if (res) {
      initData();
    }
  });
}

function onclick(evt: any, row: StockItemEDoc) {
  if (props.onClickable) {
    part_ids.value = [];

    editRow.value = { ...row };
    for (let child of childs.value) {
      if (child.description == row.stock_item.description) {
        part_ids.value.push(child.id);
      }
    }
    if (part_ids.value.length == 0) {
      part_ids.value.push(props.part_id);
    }
    edocHistory.value = true;
  }
}
async function getChildParts() {
  const res = await getChildPartsList(props.stockCode, props.serialNo);
  if (res.data) {
    console.log(res.data);

    childs.value = res.data;
  }
}
onMounted(() => {
  if (props.serialNo) {
    getChildParts();
  }
  initData();
});
</script>
